package com.fhnew.app.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;


import com.fhnew.app.R;
import com.fhnew.app.model.internet.model.ThirdGameModel;
import com.fhnew.app.util.ActivityUtil;

import com.fhnew.app.util.HLog;
import com.fhnew.app.widget.FloatButton;
import com.fhnew.app.widget.LoadingDialog;
import com.tencent.smtt.export.external.interfaces.IX5WebChromeClient;
import com.tencent.smtt.export.external.interfaces.JsResult;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.DownloadListener;
import com.tencent.smtt.sdk.QbSdk;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;


public class X5WebActivity extends AppCompatActivity {

    public static void initX5WebView(Context context){
        //搜集本地tbs内核信息并上报服务器，服务器返回结果决定使用哪个内核。
        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {
            @Override
            public void onViewInitFinished(boolean arg0) {
                // TODO Auto-generated method stub
                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
//                HLog.I("X5内核状态"+arg0);
            }

            @Override
            public void onCoreInitFinished() {
                // TODO Auto-generated method stub
//                HLog.I("X5内核初始化结束");
            }
        };
        //x5内核初始化接口
        QbSdk.initX5Environment(context.getApplicationContext(),  cb);
    }

    public static void startActivity (Context context, String url, int game_id, int portrait) {
        Intent intent = new Intent(context, X5WebActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("game_id", game_id);
        intent.putExtra("portrait", portrait);
        context.startActivity(intent);
    }

    //=====================================================================

//    private static  String mHomeUrl = "http://app.html5.qq.com/navi/index";
//	  private static  String mHomeUrl = "http://soft.imtt.qq.com/browser/tes/feedback.html";
//    private static  String mHomeUrl = "http://debugtbs.qq.com";

    private String url;
    private int game_id;
    private int portrait;

    private WebView webView;
    private FloatButton floatButton;

    private LoadingDialog loadingDialog;

    private void initView(){
        webView = findViewById(R.id.webView_x5web);
        webView.setBackgroundColor(Color.parseColor("#483D8B"));
        floatButton = findViewById(R.id.floatButton);
        floatButton.setOnClickListener(onClickListener);

        loadingDialog    = new LoadingDialog((ViewGroup)findViewById(android.R.id.content).getRootView());
        loadingDialog.setLodingDialogListener(lodingDialogListener);
        loadingDialog.setDialogCancelable(false);
        loadingDialog.setShowTips(true);
    }

    private void initInfoView(){
        webView.loadUrl(url);
        loadingDialog.showLoading();
        switch (portrait) {
            case 0:
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
                break;
            case 1:
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
                break;
            case 2:
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
                break;
        }
    }

    @Override
    protected void onCreate (@Nullable Bundle savedInstanceState) {
        ActivityUtil.fullScreen(this);
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_x5web);
        initView();

        initInfo();
    }

    @Override
    protected void onResume () {
        super.onResume();
        initInfoView();
        webView.onResume();
    }

    @Override
    protected void onPause () {
        super.onPause();
        webView.onPause();
    }

    @Override
    protected void onStop () {
        super.onStop();
    }

    @Override
    protected void onDestroy () {
        super.onDestroy();
        thirdGameModel.getThirdMoneyChange(game_id);

        webView.clearCache(true);
        webView.destroy();
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick (View v) {
            HLog.I("点击");
            finish();
        }
    };

    private LoadingDialog.LodingDialogListener lodingDialogListener = new LoadingDialog.LodingDialogListener() {
        @Override
        public void cancelAction () {
            finish();
        }
    };

    @Override
    //设置回退
    public boolean onKeyDown (int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            if (webView.canGoBack()) {
                webView.goBack(); //调用goBack()返回WebView的上一页面
            } else {
                finish();
            }
            return true;
        }
        return false;
    }

    private ThirdGameModel thirdGameModel;

    private void initInfo(){
        initWebViewSettings();
        initWebClient();

        thirdGameModel = ThirdGameModel.getInstance(this);

        Intent intent = getIntent();
        url = intent.getStringExtra("url");
        game_id = intent.getIntExtra("game_id",0);
        portrait = intent.getIntExtra("portrait",0);

    }


    //===============================================================================
    //  配置WebView
    //===============================================================================

    private void initWebViewSettings() {
        WebSettings webSetting = webView.getSettings();
        //==================WebView配置======================================
        webSetting.setJavaScriptEnabled(true);//允许运行JavaScript
        webSetting.setDomStorageEnabled(true);
        //不支持缓存
        webSetting.setCacheMode(android.webkit.WebSettings.LOAD_NO_CACHE);
        //支持屏幕缩放
        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(true);
        //http和https混合加载
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSetting.setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        //================X5WebView配置=================================
        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(true);
        // webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true);
        // webSetting.setDatabaseEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        // this.getSettingsExtension().setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);//extension
        webSetting.setAppCachePath(this.getDir("appcache", 0).getPath());
        webSetting.setDatabasePath(this.getDir("databases", 0).getPath());
        webSetting.setGeolocationDatabasePath(this.getDir("geolocation", 0)
                .getPath());
        // webSetting.setPreFectch(true);

        CookieSyncManager.createInstance(this);
        CookieSyncManager.getInstance().sync();
    }

    private void initWebClient (){
        webView.setWebViewClient(client);
        webView.setWebChromeClient(webChromeClient);
        webView.setDownloadListener(downloadListener);
    }

    private WebViewClient client = new WebViewClient() {

        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if(url.contains("http://")||url.contains("https://")){
                view.loadUrl(url);
                return true;
            }
            return super.shouldOverrideUrlLoading(view,url);
        }

        @Override
        public void onPageFinished(WebView view, String url){
            super.onPageFinished(view, url);
            if(url.equals(url)){
                loadingDialog.dismiss();
            }
        }
    };

    private WebChromeClient webChromeClient = new WebChromeClient(){
        @Override
        public boolean onJsConfirm(WebView arg0, String arg1, String arg2,
                                   JsResult arg3) {
            return super.onJsConfirm(arg0, arg1, arg2, arg3);
        }

        /**
         * 全屏播放配置
         */
        @Override
        public void onShowCustomView(View view, IX5WebChromeClient.CustomViewCallback customViewCallback) {
        }

        @Override
        public void onHideCustomView() {
        }

        @Override
        public boolean onJsAlert(WebView arg0, String arg1, String arg2,
                                 JsResult arg3) {
            return super.onJsAlert(null, arg1, arg2, arg3);
        }

        @Override
        public boolean onCreateWindow (WebView webView, boolean b, boolean b1, Message message) {
            return super.onCreateWindow(webView, b, b1, message);
        }

    };

    private DownloadListener downloadListener = new DownloadListener() {
        @Override
        public void onDownloadStart (String s, String s1, String s2, String s3, long l) {

        }
    };

}
